#define _CRT_SECURE_NO_WARNINGS 1
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:

    TreeNode* reverseOddLevels(TreeNode* root) {
        queue<TreeNode*> q;
        q.push(root);
        if (root == NULL)return NULL;
        int isodd = 0;
        while (!q.empty()) {
            int sz = q.size();
            vector<TreeNode*> temp;
            for (int i = 0; i < sz; i++) {
                TreeNode* t = q.front();
                q.pop();
                if (isodd) {
                    temp.push_back(t);
                }
                if (t->left)q.push(t->left);
                if (t->right)q.push(t->right);
            }
            if (isodd) {
                for (int i = 0, j = sz - 1; i < j; i++, j--) {
                    swap(temp[i]->val, temp[j]->val);
                }
            }

            isodd = 1 - isodd;
        }
        return root;

    }
};